package p2p;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.mpisws.p2p.filetransfer.FileReceipt;
import org.mpisws.p2p.filetransfer.FileTransfer;
import org.mpisws.p2p.filetransfer.FileTransferImpl;

import rice.Continuation;
import rice.p2p.commonapi.appsocket.AppSocket;
import rice.p2p.commonapi.appsocket.AppSocketReceiver;
import rice.p2p.util.rawserialization.SimpleOutputBuffer;

public class SyncFileAppSocketSender implements AppSocketReceiver {

	private SyncFileApp app;
	private String fileName;
	
	public SyncFileAppSocketSender(SyncFileApp app, String fileName)
	{
		this.app = app;
		this.fileName = fileName;
	}
	@Override
	public void receiveException(AppSocket arg0, Exception arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void receiveSelectResult(AppSocket arg0, boolean arg1, boolean arg2)
			throws IOException {
		// TODO Auto-generated method stub

	}

	/**
     * Called when the socket comes available.
     */
    public void receiveSocket(AppSocket socket) {        
      // create the FileTransfer object
      FileTransfer sender = new FileTransferImpl(socket, null, app.node.getEnvironment());         
      
      // add the listener
      sender.addListener(new SyncFileListener());
     
      // Create a simple 4 byte message
      ByteBuffer sendMe = ByteBuffer.allocate(4);
      sendMe.put((byte)1);
      sendMe.put((byte)2);
      sendMe.put((byte)3);
      sendMe.put((byte)4);
      
      // required when using a byteBuffer to both read and write
      sendMe.flip();
      
      // Send the message
      System.out.println("Sending "+sendMe);        
      sender.sendMsg(sendMe, (byte)1, null);
      
      try {
        // get the file
        final File f = new File(this.fileName);
        
        // make sure it exists
        if (!f.exists()) {
          System.err.println("File "+f+" does not exist.  Error sending the file.");
          System.exit(1);
        }
        
        // serialize the filename
        SimpleOutputBuffer sob = new SimpleOutputBuffer();
        sob.writeUTF(f.getName()+":" + app.catalogo.get_timestamp(f.getName()));
        
        // request transfer of the file with priority 2
        sender.sendFile(f,sob.getByteBuffer(),(byte)2,new Continuation<FileReceipt, Exception>() {

          public void receiveException(Exception exception) {
            System.out.println("Error sending: "+f+" "+exception);
          }

          public void receiveResult(FileReceipt result) {
           // System.out.println("Send complete: "+result.getMetadata());
          }
        });
        
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    } 

}
